package com.xxwy.springboot.routerfunction.handler;

import com.xxwy.springboot.routerfunction.document.User;
import com.xxwy.springboot.routerfunction.repository.UserRepository;
import com.xxwy.springboot.routerfunction.util.CheckUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author xxwy
 * on 2018/8/17 0017
 */
@Component
public class UserHandler {


    private final UserRepository userRepository;

    public UserHandler(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Mono<ServerResponse> getAllUser(ServerRequest request){
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(this.userRepository.findAll(),User.class);
    }

    /**
     * 创建
     */
    public Mono<ServerResponse> insertUser(ServerRequest request){
        //注意：使用响应式的时候，Mono流,Flux流实际上是一个发布者，
        // 任何时候我们自己不能消费者流，要交给框架消费，要不然就不异步了，就阻塞了
        Mono<User> mono = request.bodyToMono(User.class);

        return mono.flatMap(user -> {

            //校验代码
            CheckUtil.checkName(user.getName());

            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(this.userRepository.save(user),User.class);

        });


    }

    /**
     * 删除
     */
    public Mono<ServerResponse> deletetUser(ServerRequest request){
        String id = request.pathVariable("id");
        return this.userRepository.findById(id).flatMap(user -> userRepository.delete(user))
                .then(ServerResponse.ok().build())
                .switchIfEmpty(ServerResponse.notFound().build());
    }
}
